import 'dart:convert';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import '../Robot.dart';
import '../details.dart';
import '../pojo.dart';

class ShangpinkuProvider extends ChangeNotifier {
  // 固定 10 个初始颜色
  final List<Color> _colors = [
    Colors.red,
    Colors.green,
    Colors.blue,
    Colors.yellow,
    Colors.orange,
    Colors.purple,
    Colors.cyan,
    Colors.teal,
    Colors.pink,
    Colors.amber,
  ];

  List<Color> get colors => _colors;

  void changeColor(int index) {
    // 随机更改特定索引的颜色
    _colors[index] =
        Colors.primaries[Random().nextInt(Colors.primaries.length)];
    notifyListeners(); // 通知监听器更新
  }

  List<Commodity> _products = [];

  bool _isLoading = false;

  List<Commodity> get products => _products;

  bool get isLoading => _isLoading;
  final String name = "name";

  Future<void> getCompanyProduct() async {
    print("getCompanyProduct start");
    _isLoading = true;
    notifyListeners();
    final accessToken = Robot.accessToken;
    final userId = Robot.userId;
    final companyId = Robot.companyId;

    FetchDataRequest2 request = FetchDataRequest2(fetchSize: fetchSize);


    const String url = "https://applet.xmlights.com/product/commodity/page";
    final uri = Uri.parse(url).replace(
      queryParameters: {
        "access_token": accessToken,
        "userId": userId,
        "companyId": companyId,
      },
    );

    final response = await http.post(
      uri,
      headers: {"Content-Type": "application/json; charset=UTF-8"},
      body: jsonEncode(request.toJson()),
    );

    if (response.statusCode == 200) {
      print("商品库：" + response.body);
      final Map<String, dynamic> jsonResponse = json.decode(response.body);
      _isLoading = false;
      print("getCompanyProduct end");
      var a = ApiResponse2<Data5>.fromJson(
        jsonResponse,
        (data) => Data5.fromJson(data),
      );
      _products = a.data!.list;
      notifyListeners();
      return;
    } else {
      throw Exception('Failed to fetch products: ${response.reasonPhrase}');
    }
  }

  Future<int> login() async {
    print("login start");
    var url = Uri.https(host, 'robot/login');
    var response = await http.post(url, body: {'sn': Robot.sn});
    var a = ApiResponse<LoginBean>.fromJson(
      jsonDecode(response.body),
      (data) => LoginBean.fromJson(data),
    ); // 传递一个从 JSON 解析 LoginBean 的方法);

    print(a.data.toString());
    if (a.data?.userId == null) {
      print('请扫码');
      return 0;
    }
    Robot.userId = a.data!.userId!;
    Robot.companyId = a.data!.companyId!;
    Robot.accessToken = a.data!.accessToken!;
    print("Robot.accessToken:" + Robot.accessToken);
    print("login end");
    return 1;
  }
}
const   fetchSize = 24;